package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.DateFormates;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.Course;
import com.example.educationalsystem.entity.Student;
import com.example.educationalsystem.entity.Teacher;
import com.example.educationalsystem.entity.User;
import com.example.educationalsystem.entity.Vo.CourseVo;
import com.example.educationalsystem.service.IStudentService;
import com.example.educationalsystem.service.ITeacherService;
import com.example.educationalsystem.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-02
 */
@Api(value = "/student",tags = "学生信息管理")
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private IStudentService iStudentService;

    @Autowired
    private IUserService iUserService;

    @GetMapping("/getAllStudent")
    @ApiOperation(value = "获取所有学生信息",notes = "获取所有学生信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllStudent()
    {
        ResponseJson responseJson=new ResponseJson();
        List<Student> studentlist=iStudentService.getBaseMapper().selectList(Wrappers.lambdaQuery());
        if(studentlist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(studentlist);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无学生信息！");
        }
        return responseJson;
    }

    @ApiOperation(value = "分页查询学生信息", notes = "分页查询学生信息，需要提供页数和一页大小（即一页几条数据）")
    @GetMapping(value = "/studentpage")
    @ResponseBody
    public ResponseJson userpage(@RequestParam long current, @RequestParam long size) {
        ResponseJson responseJson = new ResponseJson();
        Page<Student> studentPage = new Page<>(current, size);
        Page<Student> studentPages = iStudentService.getBaseMapper().selectPage(studentPage, null);
        responseJson.setMsg("分页查询成功");
        responseJson.setData(studentPages);
        responseJson.setStatus(200);
        return responseJson;
    }
    @ApiOperation(value = "导出学生信息",notes = "导出学生信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
//        System.out.println(iStudentServic.toString());
        EasyExcel.write(response.getOutputStream(), Student.class).sheet(tableName).doWrite(iStudentService.getBaseMapper().selectList(Wrappers.lambdaQuery()));
    }
    @ApiOperation(value = "导入学生信息",notes = "导入学生信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, Student.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Student student = (Student) list.get(i);
                    System.out.println(student.toString());
                    //使用mybatis-plus添加到数据库
                    iStudentService.save(student);
                    User  registerUser=new User();
                    registerUser.setUserEmail("");
                    registerUser.setUserPermissions(1);
                    registerUser.setUserAvatarUrl("");
                    registerUser.setUserId(0);
                    registerUser.setUserPhone("");
                    registerUser.setUserIdentity("学生");
                    String mm = new BCryptPasswordEncoder().encode("123456");
                    registerUser.setUserPassword(mm);
                    registerUser.setUserName(student.getStudentId());
                    iUserService.save(registerUser);
                }
            }
            responseJson.setStatus(200);
            responseJson.setMsg("导入成功！");
        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg("导入失败！");
            e.printStackTrace();
        }

        return responseJson;
    }
    @ApiOperation(value = "批量删除学生信息",notes = "根据学生编号，删除多条学生信息")
    @DeleteMapping("/deleteStudents")
    @ResponseBody
    public  ResponseJson deleteStudents( @ApiParam(name = "Ids", value = "学生IDs", required = true) @RequestParam String Ids)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        for(int i=0;i<idList.size();i++)
        {
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            iUserService.getBaseMapper().delete(userQueryWrapper.eq("user_name",iStudentService.getById(idList.get(i)).getStudentId()));
        }
        boolean result=iStudentService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }
    @ApiOperation(value = "增加学生信息",notes = "增加一条学生信息记录")
    @PostMapping("/insertStudent")
    @ResponseBody
    public ResponseJson insertStudent(@RequestBody Student requestStudent)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        String strID = DateFormates.NowDateFormate();
        requestStudent.setStudentId(strID);
        Student studentOne=iStudentService.getBaseMapper().selectOne(queryWrapper.eq("student_id",requestStudent.getStudentId()));
        if(studentOne==null)
        {
            Boolean result=iStudentService.save(requestStudent);
            User  registerUser=new User();
            registerUser.setUserEmail("");
            registerUser.setUserPermissions(1);
            registerUser.setUserAvatarUrl("");
            registerUser.setUserId(0);
            registerUser.setUserPhone("");
            registerUser.setUserIdentity("学生");
            String mm = new BCryptPasswordEncoder().encode("123456");
            registerUser.setUserPassword(mm);
            registerUser.setUserName(requestStudent.getStudentId());
            iUserService.save(registerUser);
            if(result)
            {
                responseJson.setMsg("增加成功！");
                responseJson.setStatus(200);
                responseJson.setData(requestStudent);

            }
            else
            {
                responseJson.setStatus(400);
                responseJson.setMsg("增加失败！");
            }
        }
        else
        {
            responseJson.setStatus(400);
            responseJson.setMsg("该学生信息已存在！");
        }
        return responseJson;
    }


    @ApiOperation(value = "删除学生信息",notes = "根据学号，删除一条学生信息")
    @DeleteMapping("/deleteStudent")
    @ResponseBody
    public  ResponseJson deleteStudent( @ApiParam(name = "studentId", value = "学号", required = true) @RequestParam String studentId)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        Student studentOne=iStudentService.getBaseMapper().selectOne(queryWrapper.eq("student_id",studentId));
        if(studentOne!=null)
        {
            int result=iStudentService.getBaseMapper().deleteById(studentOne.getStudentId());
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            iUserService.getBaseMapper().delete(userQueryWrapper.eq("user_name",studentOne.getStudentId()));
            System.out.println(result);
            if(result==1)
            {
                responseJson.setData(studentOne);
                responseJson.setMsg("删除成功！");
                responseJson.setStatus(200);
            }
            else
            {
                responseJson.setMsg("删除失败");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("该学生信息不存在！");
        }
        return responseJson;

    }

    @ApiOperation(value = "更新学生信息",notes = "更新学生信息，必须填写学生ID")
    @PutMapping("/updateStudent")
    @ResponseBody
    public ResponseJson updateStudent(@RequestBody  Student resquestStudent)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        Student studentOne=iStudentService.getBaseMapper().selectOne(queryWrapper.eq("student_id",resquestStudent.getStudentId()));
        if(studentOne!=null)
        {
            int result=iStudentService.getBaseMapper().updateById(resquestStudent);
            if(result==1)
            {
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
                responseJson.setData(resquestStudent);
            }
            else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setMsg("该学生信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;
    }
}

